package com.yinhai.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.lz.util.SystemParsUtils;
import com.yinhai.adapter.ContactDelContactListAdpter;
import com.yinhai.model.ContactsUser;
import com.yinhai.util.NullUtils;

/**
 * MsgQFActivity （集团短信群发）
 * 
 * @author lz
 */
public class MsgQFActivity extends Activity {
    private AQuery aq = null;
    
    private EditText dialogEdit, smsTel;
    
    private ListView contactListView;
    
    private ContactDelContactListAdpter smsAdpter;
    
    private List<ContactsUser> list = new ArrayList<ContactsUser>();
    
    private int textCount = 1;
    
    private int maxTextCount = 918;
    
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    
    private ProgressDialog mpDialog;
    
    private Handler myHandler;
    
    private boolean sendSMS = true;
    
    public final static String NameFX =
        "我正在使用集团通信录,单位内部沟通联系真的很方便,你也试一试,集团通信录下载地址:http://111.10.24.47:8888/imserver/a.htm";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dxqf);
        
        aq = new AQuery(this);
        
        aq.id(R.id.tv_jt).clicked(Btn_tv_jt);
        aq.id(R.id.tv_tj).clicked(Btn_tv_tj);
        aq.id(R.id.tv_sj).clicked(Btn_tv_sj);
        aq.id(R.id.tv_del).clicked(Btn_tv_del);
        contactListView = (ListView)this.findViewById(R.id.listview);
        smsAdpter = new ContactDelContactListAdpter(this, list, true);
        contactListView.setAdapter(smsAdpter);
        contactListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // CheckBox checkBox = (CheckBox) view.findViewById(R.id.btn_check);
                // checkBox.setChecked(!checkBox.isChecked());
                // list.get(Integer.valueOf(view.getTag().toString()));
                list.remove(position);
                
                aq.id(R.id.tv_conut).text("用户数：" + list.size());
                smsAdpter.notifyDataSetChanged();
            }
        });
        
        Intent it = getIntent();
        if (it != null) {
            int isFx = it.getIntExtra("IsFx", 0);
            if (isFx == 1) {
                // String
                // name="我正在使用集团通讯录,单位内部沟通联系真的很方便,你也试一试,集团通讯录下载地址http://111.10.24.46:8888/imserver/getAndroidApk?apkName=group-android-app";
                textCount = NameFX.length();
                aq.id(R.id.edtContent).text(NameFX);
                aq.id(R.id.tvInputCount).text((maxTextCount) + "/" + textCount);
            }
        }
        
        aq.id(R.id.edtContent).getEditText().addTextChangedListener(etContentWatcher);
        
        // 短信发送
        this.findViewById(R.id.sms_send).setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                if (aq.id(R.id.edtContent).getText().toString().trim().equals("")) {
                    Toast.makeText(MsgQFActivity.this, "请填写短信内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (NullUtils.isNotEmpty(list) && list.size() >= 30) {
                    new AlertDialog.Builder(MsgQFActivity.this).setTitle("操作提示")
                        .setMessage("群发短信人数超过30人，短信不一定会发送成功,是否发送")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                mpDialog.show();
                                new SendSMSThread(MsgQFActivity.this).start();
                                arg0.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                arg0.dismiss();
                                
                            }
                        })
                        .show();
                } else {
                    mpDialog.show();
                    new SendSMSThread(MsgQFActivity.this).start();
                }
                
            }
        });
        
        aq.id(R.id.sms_send_qm).clicked(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String name = aq.id(R.id.edtContent).getText().toString();
                String m = SystemParsUtils.getInstance(MsgQFActivity.this).getString("messageSign");
                if (m.equals("")) {
                    m = "签名";
                }
                
                aq.id(R.id.edtContent).text(name + "\r\n" + m);
                
                CharSequence text = aq.id(R.id.edtContent).getText();
                if (text instanceof Spannable) {
                    Spannable spanText = (Spannable)text;
                    Selection.setSelection(spanText, text.length());
                }
                
            }
        });
        mpDialog = new ProgressDialog(this);
        mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
        mpDialog.setTitle("提示");// 设置标题
        // mpDialog.setIcon(R.drawable.icon);//设置图标
        mpDialog.setMessage("正在发送短信...");
        // mpDialog.setIndeterminate(false);//设置进度条是否为不明确
        mpDialog.setCancelable(false);// 设置进度条是否可以按退回键取消
        
        myHandler = new Handler() {
            public void handleMessage(Message msg) {
                Bundle bundle = msg.getData();
                int success = bundle.getInt("success");
                int failed = bundle.getInt("failed");
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        
                        // mpDialog.dismiss();
                        if (MsgQFActivity.this.sendSMS) {
                            // Toast.makeText(getApplicationContext(), "短信发送完毕！",Toast.LENGTH_LONG).show();
                            mpDialog.setMessage("正在发送短信...");
                            mpDialog.dismiss();
                            new AlertDialog.Builder(MsgQFActivity.this).setTitle("提示")
                                .setMessage("短信发送完毕！" + success + "/" + list.size())
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                            aq.id(R.id.edtContent).text("");
                            list.clear();
                            aq.id(R.id.tv_conut).text("用户数：" + list.size());
                            smsAdpter.notifyDataSetChanged();
                        }
                        break;
                    case 1:
                        mpDialog.setMessage("正在发送短信...   " + success + "/" + list.size());
                }
                
            }
        };
        
        // this.registerReceiver(smsReceiver, new IntentFilter(SENT_SMS_ACTION));
    }
    
    private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context _context, Intent _intent) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(MsgQFActivity.this, "短信发送成功", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    break;
            }
        }
    };
    
    /**
     * 监控输入字数
     * */
    TextWatcher etContentWatcher = new TextWatcher() {
        
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            textCount = textCount + count - before;
            if (textCount <= maxTextCount) {
                aq.id(R.id.tvInputCount).text((maxTextCount) + "/" + textCount);
            } else {
                aq.id(R.id.tvInputCount).text(maxTextCount + "/" + maxTextCount);
            }
        }
        
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            
        }
    };
    
    /**
     * 全部清楚
     * 
     * @param view
     */
    OnClickListener Btn_tv_del = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            aq.id(R.id.tv_conut).text("用户数：" + 0);
            smsAdpter.clear();
            smsAdpter.notifyDataSetChanged();
        }
    };
    
    /**
     * 集团通讯录
     * 
     * @param view
     */
    OnClickListener Btn_tv_jt = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(MsgQFActivity.this, ContactActivity.class);
            intent.putExtra("userType", 2);
            intent.putExtra("isMutiCheck", true);
            startActivityForResult(intent, 12345678);
        }
    };
    
    /**
     * 手机联系人
     * 
     * @param view
     */
    OnClickListener Btn_tv_sj = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(MsgQFActivity.this, ContactActivity.class);
            intent.putExtra("userType", 1);
            intent.putExtra("isMutiCheck", true);
            startActivityForResult(intent, 12345678);
        }
    };
    
    /**
     * 
     * 手动添加
     */
    OnClickListener Btn_tv_tj = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            dialogEdit = new EditText(MsgQFActivity.this);
            dialogEdit.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            dialogEdit.setHint("提示:多个号码以逗号分隔");
            dialogEdit.setInputType(InputType.TYPE_CLASS_PHONE);
            new AlertDialog.Builder(MsgQFActivity.this).setTitle("请输入短信号码")
                .setView(dialogEdit)
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        
                        if (!dialogEdit.getText().toString().equals("")) {
                            if (dialogEdit.getText().toString().indexOf(",") > 0) {
                                for (String str : dialogEdit.getText().toString().split(",")) {
                                    ContactsUser user = new ContactsUser();
                                    user.setName(str);
                                    user.setTelPhone(str);
                                    list.add(user);
                                    smsAdpter.notifyDataSetChanged();
                                }
                            } else {
                                ContactsUser user = new ContactsUser();
                                user.setName(dialogEdit.getText().toString());
                                user.setTelPhone(dialogEdit.getText().toString());
                                list.add(user);
                                smsAdpter.notifyDataSetChanged();
                            }
                            aq.id(R.id.tv_conut).text("用户数：" + list.size());
                            
                        }
                        
                    }
                })
                .show();
        }
    };
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 12345678 && resultCode == RESULT_OK) {
            for (ContactsUser user : (List<ContactsUser>)data.getSerializableExtra("data")) {
                list.add(user);
            }
            aq.id(R.id.tv_conut).text("用户数：" + list.size());
            smsAdpter.notifyDataSetChanged();
        }
    }
    
    @Override
    protected void onDestroy() {
        // unregisterReceiver(smsReceiver);
        super.onDestroy();
    }
    
    public void doBack(View view) {
        onBackPressed();
    }
    
    private class SendSMSThread extends Thread {
        private MsgQFActivity context;
        
        public SendSMSThread(MsgQFActivity context) {
            this.context = context;
        }
        
        public void run() {
            try {
                
                int success = 0;
                Intent sentIntent = new Intent(SENT_SMS_ACTION);
                PendingIntent sentPI = PendingIntent.getBroadcast(MsgQFActivity.this, 0, sentIntent, 0);
                ArrayList<PendingIntent> Pendinglist = new ArrayList<PendingIntent>();
                Pendinglist.add(sentPI);
                SmsManager smsManager = SmsManager.getDefault();
                String content = aq.id(R.id.edtContent).getText().toString().trim();
                ArrayList<String> divideContents = smsManager.divideMessage(content);
                for (ContactsUser str : list) {
                    smsManager.sendMultipartTextMessage(str.getTelPhone() + "", null, divideContents, Pendinglist, null);
                    ContentValues values = new ContentValues();
                    // 发送时间
                    values.put("date", System.currentTimeMillis());
                    // 阅读状态
                    values.put("read", 0);
                    // 1为收 2为发
                    values.put("type", 2);
                    // 送达号码
                    values.put("address", str.getTelPhone() + "");
                    // 送达内容
                    values.put("body", content);
                    // 插入短信库
                    getContentResolver().insert(Uri.parse("content://sms/sent"), values);
                    Bundle data = new Bundle();
                    success++;
                    data.putInt("success", success);
                    Message msg = new Message();
                    msg.setData(data);
                    msg.what = 1;
                    MsgQFActivity.this.myHandler.sendMessage(msg);
                    Thread.sleep(50);
                    if (!context.sendSMS) {
                        break;
                    }
                }
                
                Message msg = new Message();
                msg.what = 0;
                Bundle data = new Bundle();
                data.putInt("success", success);
                msg.setData(data);
                MsgQFActivity.this.myHandler.sendMessage(msg);
                
            } catch (Exception e) {
                e.printStackTrace();
                // Loger.e("发送短信发生异常");
            }
        }
        
    }
    
}
